<template>
    <el-image
        ref="imageRef"
        style="width: 1px; height: 1px"
        :src="srcTest"
        :zoom-rate="1.2"
        :max-scale="7"
        :min-scale="0.2"
        :preview-src-list="srcListTest"
        :initial-index="startIndex"
        fit="cover"
        @switch="getCurrent"
    >

    <!-- 自定义预览内容（#viewer插槽） -->
      <template #viewer>
        <div class="custom-preview-container">
          <div style="display: flex;width: 100%;justify-content: center;">
            <TempTest :item="item"></TempTest>
          </div>
          <div style="width: auto;margin-top: 800px" v-if="popoverVisible">
            <TagSelect   :model-value="remoteSelectTest.modelValue"
                         :placeholder="remoteSelectTest.placeholder"
                         :fetch-options="remoteSelectTest.fetchOptions"
                         :api="remoteSelectTest.api"
                         :data="srcTest"
                         @update:modelValue="sureChange"
                         :field-mappings="remoteSelectTest.fieldMappings"
                         @modelEntry="newOneItem"
                         @focusout="switchInput"
                         @keydown="handleKeydown"
                         ref="tagSelectRef"
            ></TagSelect>
          </div>
        </div>
      </template>

      <template
          #toolbar="{ actions, prev, next, reset, activeIndex, setActiveItem }"
      >
        <el-icon @click="prev">
          <Back/>
        </el-icon>
        <el-icon @click="next">
          <Right/>
        </el-icon>
        <el-icon @click="actions('zoomOut')">
          <ZoomOut/>
        </el-icon>
        <el-icon
            @click="actions('zoomIn', { enableTransition: false, zoomRate: 2 })"
        >
          <ZoomIn/>
        </el-icon>
        <el-icon
            @click="
            actions('clockwise', { rotateDeg: 180, enableTransition: false })
          "
        >
          <RefreshRight/>
        </el-icon>

        <el-icon @click="switchInput" >
          <RefreshRight/>
        </el-icon>
      </template>
    </el-image>

</template>

<script setup lang="ts">
import {onBeforeUnmount, onMounted, reactive, ref} from "vue";

// 导入本地图片  1685*802
import TempTest from "@/views/club/life/Compent/TempTest.vue";
import TagSelect from "@/views/club/life/Compent/TagSelect.vue";
import {
  Back,
  RefreshRight,
  Right,
  ZoomIn,
  ZoomOut
} from "@element-plus/icons-vue";
import {ElIcon} from "element-plus";
import {remoteTagApi} from "@/api/modules/novel/chararterTag";
import {useDictOptions} from "@/hooks/useDictOptions";


// 使用本地图片路径
let item = ref([]);
let orginalData = ref([])
let imageRef = ref();
let tagSelectRef = ref();
let srcTest =ref('')
let srcListTest =ref([])
let startIndex = ref(0);
let popoverVisible = ref(false);
const colorArr = useDictOptions('tagColor');


let getCurrent = (index :any) => {
  let targetTag = orginalData.value[index]
  item.value = targetTag.item
  //修改select绑定的值
  if (popoverVisible.value){
    tagSelectRef.value.newSrcUrl = targetTag.src
  }
};


let handleKeydown = (event :any) => {

  if (event.keyCode === 9) {
    var rightArrowEvent = new KeyboardEvent('keydown', {
      keyCode: 39,  // 39是右方向键的keyCode
      key: 'ArrowRight',
      code: 'ArrowRight',
      which: 39,
      bubbles: true
    });
    document.dispatchEvent(rightArrowEvent);
    event.preventDefault();  // 阻止空格键的默认行为
  }

  if (event.keyCode === 32) {
    event.preventDefault();  // 阻止空格键的默认行为
  }
};


let switchInput = () => {
  popoverVisible.value = !popoverVisible.value;
};

let remoteSelectTest = reactive({
  modelValue: '',
  placeholder: '输入标签名',
  fetchOptions: remoteTagApi,
  api: (query: any) => ({ keyword: query }),
  fieldMappings: {
    key: 'id',
    label: 'tagName',
    value: 'id'
  }
})

let openLifeEditDialog = (src: any,itemFrom :any,srcList :any) => {
  srcTest.value = src
  orginalData.value = srcList
  let list = srcList.map((s:any) => s.src)
  startIndex.value =list.indexOf(src);
  srcListTest.value = list
  item.value = itemFrom

  imageRef.value?.$el.querySelector('img').click()
};

/**
 * 选择了一项
 * @param option
 */
let sureChange = (newValue :any, srcUrl :any, option: any)=>{
  let target =orginalData.value.find(item=>item.src === srcUrl)
  if (target){
    let item = {
      id: option.id,
      color:option.color,
      colorName:option.colorName,
      describe:option.tagName
    }
    target.item.push(item)
  }
}
/**
 * 按下了entry
 */
let newOneItem = (keyword:any, srcUrl : any)=>{
  let total = colorArr.value.length; // Assuming colorArr is an array
  let randomIndex = Math.floor(Math.random() * total); // Generate random index
  let targetColor = colorArr.value[randomIndex]; // Get the color at the random index
  console.log('asdfwefsad234235', targetColor);
  let item = {
    color:targetColor.detailValue,
    colorName:targetColor.codeName,
    describe:keyword
  }
  console.log('JSON.parse(JSON.stringify(item))',JSON.parse(JSON.stringify(item)));

  let target =orginalData.value.find(item=>item.src === srcUrl)
  target.item.push(JSON.parse(JSON.stringify(item)));
}

defineExpose({ openLifeEditDialog });
</script>

<style scoped lang="scss">

.editTag {
  position: absolute;
  width: 100vw;
  height: 100vh;
  display: flex;
  justify-content: center;
  bottom: 50px;
  z-index: 999; /* 确保在最上层 */
}

/* 预览容器：全屏显示，左右布局 */
.custom-preview-container {
  position: absolute;
  width: 100%; /* 或设置为具体宽度 */
  display: flex;
  top: 0;
  justify-content: center;
  flex-wrap: wrap;
  z-index: 999; /* 确保在最上层 */
}

/* 左侧标题栏：固定宽度，白色背景， padding */
.custom-preview-title {
  color: black;
  width: 300px; /* 标题栏宽度（可调整） */
  height: 100vh;
  background: #fff;
  padding: 20px;
  box-shadow: 2px 0 5px rgba(0, 0, 0, 0.1); /* 右侧阴影区分 */
  overflow-y: auto; /* 标题过长时滚动 */
}

/* 标题内的关闭按钮：右上角对齐 */
.custom-preview-title .close-btn {
  position: absolute;
  top: 20px;
  right: 20px;
  cursor: pointer;
  font-size: 20px;
  color: #666;
}

/* 右侧图片预览区域：占满剩余宽度，居中显示 */
.custom-preview-image {
  flex: 1; /* 占满剩余宽度 */
  min-width: 0; /* 关键：允许Flex项目收缩到max-width以下 */
  max-width: 1685px;
  max-height: 802px;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
  box-sizing: border-box;
}

/* 调整el-image-viewer的默认样式（去除多余边距） */
.custom-preview-image .el-image-viewer__wrapper {
  margin: 0; /* 取消默认边距 */
  max-width: 100%; /* 不超过父元素的max-width */
  max-height: 100%; /* 不超过父元素的max-height */
}


.fullscreen-cropper-wrap {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  background-color: rgba(0, 0, 0, 0.85);
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  z-index: 9999;
  cursor: zoom-out;
}


.el-image {
  position: relative;
  z-index: 999;
}
/* 图片样式会由 JS 动态修改 */
</style>
